<template>
  <!-- 公共导入组件 -->
  <upload-excel :on-success="success" :before-upload="beforeUpload" />
</template>

<script>
import UploadExcel from '@/components/UploadExcel'
export default {
  components: { UploadExcel },
  methods: {
    success({ header, results }) {
      // 员工上传
      if (this.$route.query.type === 'employees') {
        this.importEmployee(results)
      } else if (this.$route.query.type === 'salarys') {
        this.$message.success('工资表上传')
      }
    },
    beforeUpload(file) {
      // console.log(file)
      const isLt1M = file.size / 1024 / 1024 < 1
      return isLt1M
    },
    // 2. 把excel的日期转成js的日期
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    },
    // 3.批量导入员工
    async importEmployee(results) {
      // 将中文键名转为英文
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const newArr = results.map(obj => {
        // 取出每一个对象
        const newObj = {}
        Object.keys(obj).forEach(key => {
          // 取出每一个key
          if (['转正日期', '入职日期'].includes(key)) {
            newObj[userRelations[key]] = this.formatDate(obj[key], '-')
          } else {
            newObj[userRelations[key]] = obj[key]
          }
        })
        return newObj
      })
      // console.log(newArr),调用接口，发送数据
      await this.apis.employees.reqAddEmployeeBatch(newArr)
      this.$message.success('批量上传员工成功')
      this.$router.back()
    }
  }
}
</script>

<style>

</style>
